from appium import webdriver
from appium.webdriver.extensions.android.nativekey import AndroidKey
import re
import time
from buy import toDell

def openApp():
  # com.eastmoney.android.berlin/.activity.MainActivity
  desired_caps = {
    'platformName': 'Android', # 被测手机是安卓
    'platformVersion': '7', # 手机安卓版本
    'deviceName': 'xxx', # 设备名，安卓手机可以随意填写
    'appPackage': 'com.eastmoney.android.berlin', # 启动APP Package名称
    'appActivity': '.activity.MainActivity', # 启动Activity名称
    'unicodeKeyboard': True, # 使用自带输入法，输入中文时填True
    'resetKeyboard': True, # 执行完程序恢复原来输入法
    'noReset': True,       # 不要重置App
    'newCommandTimeout': 6000,
    'automationName' : 'UiAutomator2'
    # 'app': r'd:\apk\bili.apk',
  }

  # 连接Appium Server，初始化自动化环境
  driver = webdriver.Remote('http://localhost:4723/wd/hub', desired_caps)

  # 设置缺省等待时间
  driver.implicitly_wait(5)

  # 点击底部自选 
  driver.find_element_by_id("com.eastmoney.android.berlin:id/btn3").click()

  # 点击组合
  driver.find_element_by_id("com.eastmoney.android.berlin:id/middle_part_item3").click()



  count =  1

  while True:
      # 新消息提示
    els3 = driver.find_elements_by_xpath("/hierarchy/android.widget.FrameLayout/android.widget.LinearLayout/android.widget.FrameLayout/android.widget.FrameLayout/android.widget.RelativeLayout/androidx.viewpager.widget.ViewPager/android.widget.LinearLayout/android.widget.LinearLayout")

    print(len(els3))
    driver.swipe(start_x=500, start_y=1050, end_x=500, end_y=1416, duration=800)
    print(f"刷新页面")
    if len(els3) > 1:
      count += 1

    # # 点击提示消息
      # els3[0].click()

      # 显示购买信息
      # results = driver.find_elements_by_id("tv_content")
      # word = results[0].text # "买入 *ST拉夏(603157),成交价2.35元"
      word =  "买入 *ST拉夏(603157),成交价2.35元"
      # 正则匹配规则
      p1 = re.compile(r'[(](.*?)[)]')

      if word[:2] == "买入":
        mode = "buy"
      elif word[:2] == "卖出":
        mode = "sell"
      
      # 正则匹配股票代码
      code = re.findall(p1,word)
      
          # 点击左上角 返回按钮
      # driver.find_element_by_id("ctv_em_titlebar_left").click()

      if code[0].startswith("0") or code[0].startswith("6"):
        print(code)
        print(driver)
        print(mode)
        try:
          toDell(code, driver,count, mode)

          # 返回
          driver.find_element_by_id("left_button").click()
        
          driver.find_element_by_id("iv_back").click()
        except :
          print("没有找到元素")
          openApp()
      
    time.sleep(8)  # 强制等待10秒时间

openApp()




